package com.share.web.action.sysmgr.privilege;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.share.bean.oa.org.EmpAccount;
import com.share.bean.oa.org.Employee;
import com.share.bean.sysmgr.privilege.PrivilegeResource;
import com.share.bean.sysmgr.privilege.PrivilegeRole;
import com.share.commons.util.MD5;
import com.share.service.oa.org.EmployeeLoginLicenceManager;
import com.share.service.oa.org.EmployeeManager;
import com.share.service.sysmgr.privilege.PrivilegeResourceManager;
import com.share.service.sysmgr.privilege.PrivilegeRoleManager;
import com.share.web.action.base.BaseActionSupport;

@Component
@Scope("prototype")
public class PrivilegeEmployeeAction extends BaseActionSupport {

	private static final long serialVersionUID = 1L;
	
	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	private String result;
	
	private boolean exist ;

	public boolean isExist() {
		return exist;
	}

	public void setExist(boolean exist) {
		this.exist = exist;
	}

	private Employee emp;

	private EmpAccount ea;

	@Resource
	private EmployeeManager empMgr;

	@Resource
	private PrivilegeRoleManager roleMgr;

	@Resource
	private PrivilegeResourceManager resMgr;

	@Resource
	private EmployeeLoginLicenceManager empCheck;

	private String empAccount;

	private String empPassword;

	private String[] roleId;

	private String[] resId;

	/**
	 * 保存员工编号，并加载角色和受保护资源
	 * 
	 * @return
	 * @throws Exception
	 */
	public String loadRoleAndRes() throws Exception {
		HttpSession session = this.getBaseform().getRequest().getSession();

		this.getBaseform().getRequest().setAttribute("emp", this.empMgr.loadByEmpNoManager(emp.getEmpNo()));
		session.setAttribute("roleList", this.roleMgr.queryRoleManager());
		session.setAttribute("resList", this.resMgr.queryResourceManager());

		return "nextRoleRes";
	}

	/**
	 * 给员工分配角色以及资源
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public String addEmpRoleRes() throws Exception {

		HttpSession session = this.getBaseform().getRequest().getSession();
		Set setRole = new HashSet();
		Set setRes = new HashSet();

		// 添加角色
		if ("addRole".equals(this.getBaseform().getType())) {
			this.getBaseform().getRequest().setAttribute("emp", this.empMgr.loadByEmpNoManager(emp.getEmpNo()));
			if (null != roleId && roleId.length > 0) {
				System.out.println("-------【ROLE】-------");
				session.removeAttribute("roleId");
				for (int i = 0; i < roleId.length; i++) {
					PrivilegeRole srole = new PrivilegeRole();
					srole.setRoleId(Integer.parseInt(roleId[i]));
					setRole.add(srole);
				}
				session.setAttribute("roleId", setRole);
				roleId = null;
				return "addEmpRes";
			} else {
				return "addEmpRes";
			}
		}

		// 添加资源
		if ("addRes".equals(this.getBaseform().getType())) {
			if (null != resId && resId.length > 0) {
				System.out.println("-------【RES】-------");
				session.removeAttribute("resId");
				for (int i = 0; i < resId.length; i++) {
					PrivilegeResource sres = new PrivilegeResource();
					sres.setResId(Integer.parseInt(resId[i]));
					setRes.add(sres);
				}
				session.setAttribute("resId", setRes);
				resId = null;
			}

			// 将员工的角色与资源全部删除
			if (null == session.getAttribute("roleId") && null == session.getAttribute("resId")) {
				Employee employee = this.empMgr.loadByEmpNoManager(emp.getEmpNo());
				employee.setRole((Set<PrivilegeRole>) session.getAttribute("roleId"));
				employee.setResource((Set<PrivilegeResource>) session.getAttribute("resId"));
				this.empMgr.updateEmpManager(employee);
			}

			// 添加或修改员工的角色与资源
			if (null != session.getAttribute("roleId") || null != session.getAttribute("resId")) {

				Employee employee = this.empMgr.loadByEmpNoManager(emp.getEmpNo());
				employee.setRole((Set<PrivilegeRole>) session.getAttribute("roleId"));
				employee.setResource((Set<PrivilegeResource>) session.getAttribute("resId"));

				this.empMgr.updateEmpManager(employee);
				employee = null;
			}
			session.removeAttribute("roleId");
			session.removeAttribute("resId");
			session.removeAttribute("emp");
			session.removeAttribute("roleList");
			session.removeAttribute("resList");
		}
		return "loadAllEmp";
	}
	
	/**
	 * 验证登录
	 * 
	 * @result 1：该账号不存在，或账号密码错误 2：该账号已经失效，员工为离职状态 3：账号验证成功，进入登陆界面
	 * @return 返回JSON
	 * @throws Exception
	 */
	public String checkLogin() {
		try {
			ea = this.empCheck.checkEmpLoginManager(empAccount, empPassword);

			if (null == ea) {
				result = "1";
				logger.info("用户【"+empAccount+"】登录失败【该账号不存在，或账号密码错误 】") ;
			}
			if (null != ea && !ea.getEmployee().isVisible()) {
				result = "2";
				logger.info("用户【"+empAccount+"】登录失败【该账号已经失效，员工为离职状态】") ;
			}
			if (null != ea && ea.getEmployee().isVisible()) {
				result = "3";
				logger.info("用户【"+empAccount+"】登录成功【账号验证成功，进入登陆界面】") ;
				getEmpInfo();
			}
			return "LoginJSON";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 修改登陆密码
	 * @return
	 * @throws Exception
	 */
	public String modifyPwd() throws Exception {
		
		exist = this.empCheck.updateEmpPwdManager(MD5.MD5Encode(ea.getPassword()), ea.getId()) ;
		
		return "modifypwd" ;
	}
	
	/**
	 * 检查账号存不存在
	 * @return
	 * @throws Exception
	 */
	public String checkAccountExist() throws Exception {
		exist = this.empCheck.checkAccountExistManager(ea.getAccount()) ;
		return "checkExistJSON" ;
	}

	/**
	 * 获得个人的全部权限
	 */
	public void getEmpInfo() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> role = new ArrayList<String>();
		List<String> res = new ArrayList<String>();

		for (Iterator<PrivilegeRole> iterator = ea.getEmployee().getRole().iterator(); iterator.hasNext();) {
			PrivilegeRole s = (PrivilegeRole) iterator.next();
			Set<PrivilegeResource> set = s.getResource();
			for (Iterator<PrivilegeResource> iterator2 = set.iterator(); iterator2.hasNext();) {
				PrivilegeResource r = (PrivilegeResource) iterator2.next();
				role.add(r.getResUrl());
			}
		}

		for (Iterator<PrivilegeResource> iterator = ea.getEmployee().getResource().iterator(); iterator.hasNext();) {
			PrivilegeResource r = (PrivilegeResource) iterator.next();
			res.add(r.getResUrl());
		}

		map.put("role", role);
		map.put("res", res);

		this.getBaseform().getRequest().getSession().setAttribute("roleresMap", map);
		this.getBaseform().getRequest().getSession().setAttribute("employee", ea);
		ea = null;
	}

	@JSON(serialize = false, deserialize = false)
	public EmpAccount getEa() {
		return ea;
	}

	@JSON(serialize = false, deserialize = false)
	public Employee getEmp() {
		return emp;
	}

	@JSON(serialize = false, deserialize = false)
	public String getEmpAccount() {
		return empAccount;
	}

	@JSON(serialize = false, deserialize = false)
	public String getEmpPassword() {
		return empPassword;
	}

	@JSON(serialize = false, deserialize = false)
	public String[] getResId() {
		return resId;
	}

	public String getResult() {
		return result;
	}

	@JSON(serialize = false, deserialize = false)
	public String[] getRoleId() {
		return roleId;
	}

	public void setEa(EmpAccount ea) {
		this.ea = ea;
	}

	public void setEmp(Employee emp) {
		this.emp = emp;
	}

	public void setEmpAccount(String empAccount) {
		this.empAccount = empAccount;
	}

	public void setEmpMgr(EmployeeManager empMgr) {
		this.empMgr = empMgr;
	}

	public void setEmpPassword(String empPassword) {
		this.empPassword = empPassword;
	}

	public void setResId(String[] resId) {
		this.resId = resId;
	}

	public void setResMgr(PrivilegeResourceManager resMgr) {
		this.resMgr = resMgr;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public void setRoleId(String[] roleId) {
		this.roleId = roleId;
	}

	public void setRoleMgr(PrivilegeRoleManager roleMgr) {
		this.roleMgr = roleMgr;
	}

}
